package hhm.wechat.utils;

import java.io.File;
import java.io.IOException;

import com.alibaba.fastjson.JSONObject;

import hhm.wechat.pojo.AccessToken;
import hhm.wechat.pojo.fbresult.WxResult;

public class WeixinUtil {
	private static final String APPID = "wx5eb52bb576182981";
	private static final String APPSECRET = "b7d6a99cb111e3e9c13370d3cb2b0642";

	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";

	private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	private static final String QUERY_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";

	private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

	private static final String GET_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";

	/**
	 * 获取access_token
	 * 
	 * @return
	 */
	public static AccessToken getAccessToken() {
		AccessToken token = new AccessToken();
		String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);

		String str = HttpClientUtil.doGet(url);

		token = JSONObject.parseObject(str, AccessToken.class);

		return token;
	}

	public static WxResult createMenu(String access_token, String menu) {

		String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", access_token);
		String str = HttpClientUtil.doPostJson(url, menu);

		return JSONObject.parseObject(str, WxResult.class);

	}

	public static WxResult upload(File file, String access_token, String type) {
		String str = null;
		String url = UPLOAD_URL.replace("ACCESS_TOKEN", access_token).replace("TYPE", type);
		try {

			str = HttpClientUtil.upload(url, file);
			System.out.println(str);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return JSONObject.parseObject(str, WxResult.class);
	}

	public static WxResult getMedia(String media_id, String access_token) {
		String url = GET_MEDIA_URL.replace("ACCESS_TOKEN", access_token).replace("MEDIA_ID", media_id);
		String str = HttpClientUtil.doGet(url);

		return JSONObject.parseObject(str, WxResult.class);
	}

}
